package org.jeecg.modules.scene.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhouwr.common.enums.MessageEventType;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.scene.entity.Scene;
import org.jeecg.modules.scene.mapper.DisplayerMapper;
import org.jeecg.modules.scene.mapper.SceneMapper;
import org.jeecg.modules.scene.service.IDisplayService;
import org.jeecg.modules.scene.vo.MessageEventCountVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: forallcn-iotps
 * @description: 数据展示服务
 * @author: zhouwr
 * @create: 2020-11-23 12:40
 * @version：1.0
 **/
@Service
public class DisplayServiceImpl extends ServiceImpl<SceneMapper, Scene> implements IDisplayService {

    @Autowired
    private DisplayerMapper displayerMapper;

    @Override
    public Scene getCurrentScene(String id) {
        Scene scene = new Scene();
        if (oConvertUtils.isEmpty(id) || "undefined".equals(id)) {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if (sysUser == null) {
                throw new RuntimeException("获取用户登录信息失败");
            }
            List<Scene> list = this.lambdaQuery().eq(Scene::getSysOrgCode, sysUser.getOrgCode()).list();
            if (list != null && list.size() > 0) {
                scene = list.get(0);
            } else {
                throw new RuntimeException("未找到当前登录用户所属场景数据");
            }
        } else {
            scene = this.getById(id);
            if (scene == null) {
                throw new RuntimeException("未找到id为：" + id + "的场景");
            }
        }
        return scene;
    }

    @Override
    public List<MessageEventCountVo> statMessageEvent(String sceneId) {
        return displayerMapper.countMessageEvent(sceneId).stream()
                .map(map -> {
                    final String code = String.valueOf(map.get("code"));
                    final Long count = map.get("count");
                    final MessageEventType messageEventType = MessageEventType.of(code);
                    return new MessageEventCountVo(messageEventType, count);
                }).collect(Collectors.toList());
    }
}
